package org.ekingstar.qd.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.ekingstar.qd.domain.DeployQdCompareCond;
import org.ekingstar.qd.domain.DeployQdSimplemeasu;
import org.ekingstar.qd.domain.QdCompareCond;
import org.ekingstar.qd.domain.QdDest;
import org.ekingstar.qd.domain.QdDomain;
import org.ekingstar.qd.domain.QdFormula;
import org.ekingstar.qd.domain.QdSimplemeasu;
import org.ekingstar.qd.domain.QdWhereClause;
import org.ekingstar.qd.service.CDestService;
import org.ekingstar.qd.service.CDoSearchService;
import org.ekingstar.qd.service.CRelationService;
import org.ekingstar.utils.SysArgUtil;

import com.ekingstar.framework.domain.Role;
import com.ekingstar.framework.domain.User;
import com.ekingstar.framework.security.UserUtil;
import com.ekingstar.framework.util.HibernateCallbackUtil;
import com.ekingstar.framework.util.Page;

/**
 * 客户端查询功能业务实现类接口
 * @author 
 */
public class CDoSearchServiceImpl implements CDoSearchService {
	private HibernateTemplate hibernateTemplate;
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}
	
	private JdbcTemplate jdbcTemplate;
	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}
	
	private CRelationService relationService;
	public void setRelationService(CRelationService relationService) {
		this.relationService = relationService;
	}
	
	private CDestService destService;
	public void setDestService(CDestService destService) {
		this.destService = destService;
	}
	
	/**
	 * @descirpt 简单查询
	 * @param strDomainId
	 * @param searchConditionIdNames
	 * @param searchConditionNames
	 * @param searchConditionValueNames
	 * @param pageNo
	 * @param pageSize
	 * @return Object[]
	 */
	public Object[] doSearch(String strDomainId,List<QdSimplemeasu> qdSimplemeasuList,String[] searchConditionIdNames,String[] searchConditionNames,String[] searchConditionValueNames,int pageNo, int pageSize){
		Object[] retString = new Object[5];		
		Page page = null;
		String  sql = "";
		int countField = 0;
		String condstrcn = "";
		String condstr = "";
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				//组装查询条件
				String strCond = "";
				if(searchConditionIdNames!=null && searchConditionIdNames.length>0 
				   &&	searchConditionNames!=null	&& searchConditionNames.length>0
				   &&	searchConditionValueNames!=null	&& searchConditionValueNames.length>0 
				   &&   searchConditionIdNames.length==searchConditionNames.length && searchConditionIdNames.length==searchConditionValueNames.length){
					for(int i=0;i<searchConditionIdNames.length;i++){ 					 
						//查询条件ID
						String id = searchConditionIdNames[i];
						//条件方式
						String type = searchConditionNames[i];
						//条件值
						String value = searchConditionValueNames[i];
						
						if(type!=null && !"".equals(type.toString().trim())){
							String[] tmpCond = new String[2];
							QdCompareCond qdCompareCond = this.getQdCompareCond(id);
							if(qdCompareCond!=null && qdCompareCond.getCol()!=null && !"".equals(qdCompareCond.getCol().toString().trim())){
								long isQuotation = qdCompareCond.getAutoSingleQuotation();
								if(isQuotation>0){
									tmpCond = this.ConvertCompType(qdCompareCond, type.toString().trim(), value, true);
								}else{
									tmpCond = this.ConvertCompType(qdCompareCond, type.toString().trim(), value, false);
								}							
							}
							
							if(tmpCond!=null && tmpCond.length>0 && tmpCond[0]!=null && !"".equals(tmpCond[0].toString().trim())){
								if(condstr!=null && !"".equals(condstr.toString().trim())){
									strCond = strCond +" and " + tmpCond[0].toString().trim();
									condstr = condstr + "######and " + tmpCond[0].toString().trim();
									condstrcn = condstrcn + "######并且 " + tmpCond[1].toString().trim();
								}else{
									strCond = tmpCond[0].toString().trim();
									condstr = tmpCond[0].toString().trim();
									condstrcn = tmpCond[1].toString().trim();
								}
							}
						}
					}				
				}
				
				String[] retSqlString = ConnectCond(strDomainId,qdSimplemeasuList,strCond);
				sql = retSqlString[0].toString();
				System.out.println("Query SQL:" +sql);
				countField = Integer.parseInt(retSqlString[1].toString());
				if(sql!=null && !"".equals(sql.toString().trim())){
					if (pageNo <= 0) pageNo = 1;
					StringBuffer sb = new StringBuffer(sql);
					Map params = new HashMap();
					HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, null,true,null, pageNo, pageSize);
					page = (Page)hibernateTemplate.execute(action);
				}
				
			}	
		}catch(Exception e){
			e.printStackTrace();
			page = null;
			sql = null;
			condstr = null;
			condstrcn = null;
		}
		retString[0]=page;
		retString[1]=sql;
		retString[2]=countField;
		retString[3]=condstr;
		retString[4]=condstrcn;
		return retString;
	}
	
	/**
	 * @descripte 拼装查询SQL语句
	 * @param strDomainId 主题ID号
	 * @param condStr     查询条件
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	private String[] ConnectCond(String strDomainId,List<QdSimplemeasu> qdSimplemeasuList, String condStr){
		String[] retStirng  = new String[2];
		String strRet = "";
		int countField = 0;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){				
				//查询字段
				String strField = "";				
				if(qdSimplemeasuList!=null && qdSimplemeasuList.size()>0){
					countField = qdSimplemeasuList.size();
					for(int i=0;i<qdSimplemeasuList.size();i++){
						QdSimplemeasu qdSimplemeasu = qdSimplemeasuList.get(i);
						if(qdSimplemeasu!=null && qdSimplemeasu.getId()!=null && !"".equals(qdSimplemeasu.getId().toString().trim())){
							String temp = "temp"+i;
							if(strField!=null && !"".equals(strField.toString().trim())){
								strField = strField+", ("+qdSimplemeasu.getCol()+") as "+temp;								
							}else{
								strField = "("+qdSimplemeasu.getCol()+") as "+temp ;
							}
						}
					}
				}
			
				//查询表
				String strTable = "";
				List<QdDest>  qdDestList = destService.getTableList(strDomainId);
				if(qdDestList!=null && qdDestList.size()>0){					
					for(int i=0;i<qdDestList.size();i++){
						QdDest qdDest = qdDestList.get(i);
						if(qdDest!=null && qdDest.getId()!=null && !"".equals(qdDest.getId().toString().trim())){
							if(strTable!=null && !"".equals(strTable.toString().trim())){
								strTable = strTable+", "+qdDest.getName();
							}else{
								strTable = qdDest.getName();
							}
						}
					}
				}
				
				//表关系
				String strRelation = "";
				QdFormula qdFormula = relationService.getRelationByDomainId(strDomainId);
				if(qdFormula!=null && qdFormula.getId()!=null && !"".equals(qdFormula.getId().toString().trim())){
					strRelation = qdFormula.getExpr();
				}
				
				//过滤条件
				String strFilter = "";
				List<QdWhereClause> qdWhereClauseList = getFilterList(strDomainId);				
				if(qdWhereClauseList!=null && qdWhereClauseList.size()>0){
					for(int i=0;i<qdWhereClauseList.size();i++){
						QdWhereClause qdWhereClause = qdWhereClauseList.get(i);
						if(qdWhereClause!=null && qdWhereClause.getId()!=null && !"".equals(qdWhereClause.getId().toString().trim())){
							if(strFilter!=null && !"".equals(strFilter.toString().trim())){
								strFilter = strFilter+" or "+" (" + qdWhereClause.getCondstr()+" )";								
							}else{
								strFilter = "(" + qdWhereClause.getCondstr()+" )";
							}
						}
					}					
				}
				
				if(strField!=null && !"".equals(strField.toString().trim()) &&	strTable!=null && !"".equals(strTable.toString().trim())){					
					strRet = "select "
								 + strField
							  +" from "
							     + strTable
							  +" where 1=1 ";
					
					if(strRelation!=null && !"".equals(strRelation.toString().trim())){
						strRet += " and "+ strRelation;
					}
					
					if(strFilter!=null && !"".equals(strFilter.toString().trim())){
						strRet+= " and ( "+strFilter+" ) ";
					}
					
					if(condStr!=null && !"".equals(condStr.toString().trim())){
						strRet+= " and ( "+condStr+" ) ";
					}	
					
					strRet = this.replaceSysParam(strRet);
				}			
			}
		}catch(Exception e){
			e.printStackTrace();
			strRet = null;
		}
		retStirng[0]=strRet;
		retStirng[1] = countField+"";
		return retStirng;
	}
	
	/**
	 * @descript 根据查询条件字段/匹配类型和值进行查询条件的组装.
	 * @param col  查询条件字段
	 * @param strType  条件类型
	 * @param value    条件值
	 * @param isQuotation 是否自动添加引号
	 * @return String
	 */
	private String[] ConvertCompType(QdCompareCond qdCompareCond,String strType,String value,boolean isQuotation){
		String[] retStr = new String[2];
		String strRet = "";	
		String strName = "";
		try{
			if(qdCompareCond!=null && qdCompareCond.getId()!=null && !"".equals(qdCompareCond.getId().toString().trim()) && strType!=null && !"".equals(strType.toString().trim())){
				strType = strType.toString().trim().toLowerCase();
				if(isQuotation){
					if(SysArgUtil.typeEqual.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() +" "+strType.toString().trim() +" '"+value.toString().trim()+"' ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" "+value.toString().trim();
						}
					}else if(SysArgUtil.typeNull.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value==null || "".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() +" " + strType.toString().trim() +" null ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim());
						}
					}else if(SysArgUtil.typeLike.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() +" " +strType.toString().trim() +" '%"+value.toString().trim()+"%' ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" "+value.toString().trim();
						}
					}else if(SysArgUtil.typeIn.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){							
							strRet = qdCompareCond.getCol().toString().trim() +" "+strType.toString().trim() +" ("+value.toString().trim()+") ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" ("+value.toString().trim()+") ";
						}
					}
				}else{
					if(SysArgUtil.typeEqual.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() +strType.toString().trim() +" "+value.toString().trim()+" ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" "+value.toString().trim();
						}
					}else if(SysArgUtil.typeNull.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value==null || "".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() + strType.toString().trim() +" null ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim());
						}
					}else if(SysArgUtil.typeLike.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){
							strRet = qdCompareCond.getCol().toString().trim() +strType.toString().trim() +" '%"+value.toString().trim()+"%' ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" "+value.toString().trim();
						}
					}else if(SysArgUtil.typeIn.indexOf("'"+strType.toString().trim()+"'")!=-1){
						if(value!=null && !"".equals(value.toString().trim())){							
							strRet = qdCompareCond.getCol().toString().trim() +strType.toString().trim() +" ("+value.toString().trim()+") ";
							strName = qdCompareCond.getName().toString().trim()+" "+getConditionTypeName(strType.toString().trim()) +" ("+value.toString().trim()+") ";
						}
					}
				}			
			}			
		}catch(Exception e){
			e.printStackTrace();
			retStr[0]=null;
			retStr[1]=null;
		}

		retStr[0]=strRet;
		retStr[1]=strName;	
		return retStr;
	}
	
	/**
	 * @descript 根据操作符获取对应的中文说明
	 * @param strType
	 * @return
	 */
	private String getConditionTypeName(String strType){
		strType = "'"+strType.toString().trim().toLowerCase()+"'";
		String retStr = "";
		if(SysArgUtil.typeEqual.indexOf(strType.toString().trim())!=-1){
			String[] codeTemp = SysArgUtil.typeEqual.split(",");
			String[] nameTemp = SysArgUtil.typeEqualName.split(",");
			for(int i=0;i<codeTemp.length;i++){
				if(codeTemp[i].toString().trim()==strType || codeTemp[i].toString().trim().equals(strType.toString().trim())){
					retStr = nameTemp[i].toString().trim();
					break;
				}
			}
		}
		
		if(SysArgUtil.typeIn.indexOf(strType.toString().trim())!=-1){
			String[] codeTemp = SysArgUtil.typeIn.split(",");
			String[] nameTemp = SysArgUtil.typeInName.split(",");
			for(int i=0;i<codeTemp.length;i++){
				if(codeTemp[i].toString().trim()==strType || codeTemp[i].toString().trim().equals(strType.toString().trim())){
					retStr = nameTemp[i].toString().trim();
					break;
				}
			}
		}
		
		if(SysArgUtil.typeLike.indexOf(strType.toString().trim())!=-1){
			String[] codeTemp = SysArgUtil.typeLike.split(",");
			String[] nameTemp = SysArgUtil.typeLikeName.split(",");
			for(int i=0;i<codeTemp.length;i++){
				if(codeTemp[i].toString().trim()==strType || codeTemp[i].toString().trim().equals(strType.toString().trim())){
					retStr = nameTemp[i].toString().trim();
					break;
				}
			}
		}
		
		if(SysArgUtil.typeNull.indexOf(strType.toString().trim())!=-1){
			String[] codeTemp = SysArgUtil.typeNull.split(",");
			String[] nameTemp = SysArgUtil.typeNullName.split(",");
			for(int i=0;i<codeTemp.length;i++){
				if(codeTemp[i].toString().trim()==strType || codeTemp[i].toString().trim().equals(strType.toString().trim())){
					retStr = nameTemp[i].toString().trim();
					break;
				}
			}
		}
		
		return retStr;
	}
	
	/**
	 * @descirpt 简单查询
	 * @param sql
	 * @param pageNo
	 * @param pageSize
	 * @return Page
	 */
	public Page doReSearch(String sql,int pageNo, int pageSize){
		Page page = null;
		try{
			if (pageNo <= 0) pageNo = 1;
			StringBuffer sb = new StringBuffer(sql);
			Map params = new HashMap();
			HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, null,true,null, pageNo, pageSize);
			//HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, params, null, pageNo, pageSize);
			page = (Page)hibernateTemplate.execute(action);
		}catch(Exception e){
			e.printStackTrace();
			page = null;
		}
		return page;
	}
	
	/**
	 * @descripte 根据主题和用户角色(系统自动获取)获取查询条件
	 * @param strDomainId 主题ID号
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List<QdCompareCond> getSearchList(String strDomainId){
		List<QdCompareCond> searchConditionList = null;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				String userId = UserUtil.getCurrentUserId();
				if(userId!=null && !"".equals(userId.toString().trim())){
					String strRoles = getRoles();	
					String hql = "";
					if(strRoles!=null){						
						searchConditionList = new ArrayList();
						hql = " from DeployQdCompareCond b where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+") and b.TQdDomain.id='"+strDomainId.toString().trim()+"' order by b.orderid ";
						ArrayList aList = new ArrayList();
						List<DeployQdCompareCond> dqcList = this.hibernateTemplate.find(hql);
						if(dqcList!=null && dqcList.size()>0){
							for(int i=0;i<dqcList.size();i++){
								DeployQdCompareCond dqc = dqcList.get(i);
								if(dqc!=null && dqc.getComparecondId()!=null && dqc.getComparecondId().getId()!=null && !"".equals(dqc.getComparecondId().getId().toString().trim())){
									if(!aList.contains(dqc.getComparecondId().getId().toString().trim())){
										aList.add(dqc.getComparecondId().getId().toString().trim());
										searchConditionList.add(dqc.getComparecondId());
									}
								}
							}
						}
						
						//hql = "select distinct b.comparecondId from DeployQdCompareCond b where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+") and b.TQdDomain.id='"+strDomainId.toString().trim()+"' order by b.orderid ";
					}else{
						hql = "select distinct b.comparecondId from DeployQdCompareCond b where 1<1 ";
						searchConditionList = this.hibernateTemplate.find(hql);	
					}
									
				}				
			}
		}catch(Exception e){
			e.printStackTrace();
			searchConditionList = null;
		}
		return searchConditionList;
	}
	
	
	/**
	 * @descripte 根据主题和用户角色(系统自动获取)获取过滤条件
	 * @param strDomainId 主题ID号
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List<QdWhereClause> getFilterList(String strDomainId){
		List<QdWhereClause> retList = null;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				String userId = UserUtil.getCurrentUserId();
				if(userId!=null && !"".equals(userId.toString().trim())){
					String strRoles = getRoles();	
					String hql = "";
					if(strRoles!=null){
						hql = "select distinct b.whereClauseId from DeployQdWhereClause b where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+") and b.TQdDomain.id='"+strDomainId.toString().trim()+"' ";
					}else{
						hql = "select distinct b.whereClauseId from DeployQdWhereClause b where 1<1 ";
					}
					retList = this.hibernateTemplate.find(hql);					
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		return retList;
	}
	
	
	/**
	 * @descripte 根据主题和用户角色(系统自动获取)获取查询字段
	 * @param strDomainId 主题ID号
	 * @param qdSimplemeasuId 查询字段ID字符串
	 * @param type 标识
	 *        1： qdSimplemeasuId参数无效
	 *        2： qdSimplemeasuId参数有效
	 * @return List
	 */
	@SuppressWarnings("unchecked")
	public List<QdSimplemeasu> getFieldList(String strDomainId,String qdSimplemeasuId, String type){
		List<QdSimplemeasu> retList = null;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				String strRoles = getRoles();
				if(type=="1" || "1".equals(type.toString().trim())){
					String userId = UserUtil.getCurrentUserId();
					if(userId!=null && !"".equals(userId.toString().trim())){						
						String hql = "";
						if(strRoles!=null){
							retList = new ArrayList();
							hql = " from DeployQdSimplemeasu b where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+") and b.TQdDomain.id='"+strDomainId.toString().trim()+"' order by b.orderid,b.simplemeasuId.orderid ";
							ArrayList aList = new ArrayList();
							List<DeployQdSimplemeasu> dqsList = this.hibernateTemplate.find(hql);
							if(dqsList!=null && dqsList.size()>0){									
								for(int i=0;i<dqsList.size();i++){
									DeployQdSimplemeasu dqs = dqsList.get(i);
									if(dqs!=null && dqs.getSimplemeasuId()!=null && dqs.getSimplemeasuId().getId()!=null && !"".equals(dqs.getSimplemeasuId().getId().toString().trim())){
										if(!aList.contains(dqs.getSimplemeasuId().getId().toString().trim())){
											aList.add(dqs.getSimplemeasuId().getId().toString().trim());
											retList.add(dqs.getSimplemeasuId());
										}
									}
								}
							}							
						}else{
							hql = "select distinct b.simplemeasuId from DeployQdSimplemeasu b where 1<1 ";
							retList = this.hibernateTemplate.find(hql);	
						}										
					}
				}
				
				if(type=="2" || "2".equals(type.toString().trim())){
					String[] strSid = qdSimplemeasuId.split("######");
					String conStr = "";
					String decodeStr = "";
					if(strSid!=null && strSid.length>0){
						for(int i =0;i<strSid.length;i++){
							if(strSid[i]!=null && !"".equals(strSid[i].toString().trim()) && !"null".equals(strSid[i].toString().trim())){
								if(conStr=="" || "".equals(conStr.toString().trim())){
									conStr = "'"+strSid[i].toString().trim()+"'";
									decodeStr = "'"+strSid[i].toString().trim()+"',"+i;									
								}else{
									conStr = conStr+",'"+strSid[i].toString().trim()+"'";
									decodeStr = decodeStr+",'"+strSid[i].toString().trim()+"',"+i;
								}
							}
						}
					}
					
					if(conStr!=null && !"".equals(conStr.toString().trim())){
						String hql = "";
						if(strRoles!=null){
							//hql = "select distinct b.simplemeasuId from DeployQdSimplemeasu b left join b.simplemeasuId where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+")  and b.simplemeasuId.id in ("+conStr+") order by decode(b.simplemeasuId.id,"+decodeStr+")";							
							hql = " from QdSimplemeasu a where a.id in (select b.simplemeasuId.id from DeployQdSimplemeasu b where b.roleId.deleteDate is null and b.roleId.id in ("+strRoles+") and b.TQdDomain.id='"+strDomainId.toString().trim()+"') and a.id in ("+conStr+") order by decode(a.id,"+decodeStr+")"; 
							
						}else{
							hql = "select distinct b.simplemeasuId from DeployQdSimplemeasu b where 1<1 ";
						}
						retList = this.hibernateTemplate.find(hql);	
					}
				}
				
			}
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		
		return retList;
	}
	
	
	/**
	 * @descripte 根据主题和用户角色(系统自动获取)判断此用户是否具有操作权限
	 * @param strDomainId 主题ID号
	 * @return boolean  true 有权限  false 无权限
	 */
	@SuppressWarnings("unchecked")
	public boolean checkRole(String strDomainId){
		boolean retb = false;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				QdDomain domain = (QdDomain)this.hibernateTemplate.get(QdDomain.class, strDomainId.toString().trim());
				if(domain!=null && domain.getId()!=null && !"".equals(domain.getId().toString().trim())){
					if(domain.getFunctionId()!=null && !"".equals(domain.getFunctionId().toString().trim())){
						String functionId = domain.getFunctionId().toString().trim();
						String userId = UserUtil.getCurrentUserId();
						if(userId!=null && !"".equals(userId.toString().trim())){							
							String hql = " from UserRole a where a.deleteDate is null  and a.TRole.deleteDate is null and a.TUser.deleteDate is null and a.TRole.id in (select b.TRole.id from RoleFunction b  where b.deleteDate is null and b.TFunction.deleteDate is null and b.TRole.deleteDate is null and b.TFunction.id='"+functionId+"') and  a.TUser.id ='"+userId.toString().trim()+"'";
							List retList = this.hibernateTemplate.find(hql);
							if(retList!=null && retList.size()>0){
								retb = true;
							}
						}
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
			retb = false;
		}
		return retb ;
	}
	
	
	
	/**
	 * @descripte 根据用户ID获取用户的角色信息集
	 * @param 无
	 * @return String 格式为 '','',''
	 */
	@SuppressWarnings("unchecked")
	private String getRoles(){
		String strRoles = null;
		try{			
			String userId = UserUtil.getCurrentUserId();
			if(userId!=null && !"".equals(userId.toString().trim())){							
				String hql = " select a.TRole from UserRole a where a.deleteDate is null  and a.TRole.deleteDate is null and a.TUser.deleteDate is null  and  a.TUser.id ='"+userId.toString().trim()+"'";
				List retList = this.hibernateTemplate.find(hql);
				if(retList!=null && retList.size()>0){
					for(int i=0;i<retList.size();i++){
						Role role = (Role)retList.get(i);
						if(role!=null && role.getId()!=null && !"".equals(role.getId().toString().trim())){
							if(strRoles==null){
								strRoles = "'"+role.getId().toString().trim()+"'";
							}else{
								strRoles = strRoles+",'"+role.getId().toString().trim()+"'";
							}
						}
					}
				}
			}			
		}catch(Exception e){
			e.printStackTrace();
			strRoles = null;
		}
		return strRoles ;
	}
	
	/**
	 * @descripte 根据查询条件的ID获取查询条件信息。
	 * @param strCompareCondId 查询条件字段对应ID号
	 * @return QdCompareCond  
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	public QdCompareCond getQdCompareCond(String strCompareCondId){
		QdCompareCond qdCompareCond = null;
		try{
			if(strCompareCondId!=null && !"".equals(strCompareCondId.toString().trim())){
				qdCompareCond = (QdCompareCond)this.hibernateTemplate.get(QdCompareCond.class, strCompareCondId.toString().trim());							
			}else{
				qdCompareCond = (QdCompareCond)this.hibernateTemplate.get(QdCompareCond.class, "");	
			}
		}catch(Exception e){
			e.printStackTrace();
			qdCompareCond = null;
		}
		return qdCompareCond;
	}
	
	/**
	 * @descripte 获取查询条件下拉列表内容。
	 * @param strCompareCondId 查询条件字段对应ID号
	 * @return List  
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	public List getOpenList(String strCompareCondId){
		List retList = new ArrayList();
		try{
			if(strCompareCondId!=null && !"".equals(strCompareCondId.toString().trim())){
				QdCompareCond qdCompareCond = (QdCompareCond)this.hibernateTemplate.get(QdCompareCond.class, strCompareCondId.toString().trim());
				if(qdCompareCond!=null && qdCompareCond.getId()!=null && !"".equals(qdCompareCond.getId().toString().trim())){
					String sql=qdCompareCond.getSql();
					if(sql!=null && !"".equals(sql.toString().trim())){
						List l = this.jdbcTemplate.queryForList(sql);
						if(l!=null && l.size()>0){
							for(int i=0;i<l.size();i++){
								ListOrderedMap lom = (ListOrderedMap)l.get(i);							
								Map t = new HashMap();
								t.put("code", lom.get(lom.get(0)));
								t.put("name", lom.get(lom.get(1)));
								retList.add(t);
							}						
						}
					}
				}				
			}
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		return retList;
	}
	
	
	/**
	 * @descripte 获取查询条件树数据内容。
	 * @param strCompareCondId 查询条件字段对应ID号
	 * @return List  
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	public String getBuilderTree(String strCompareCondId){
		String rootId = "";
		List retList = new ArrayList();
		List retProcessList = new ArrayList();
		String jasonString = "";
		try{
			if(strCompareCondId!=null && !"".equals(strCompareCondId.toString().trim())){
				QdCompareCond qdCompareCond = (QdCompareCond)this.hibernateTemplate.get(QdCompareCond.class, strCompareCondId.toString().trim());
				if(qdCompareCond!=null && qdCompareCond.getId()!=null && !"".equals(qdCompareCond.getId().toString().trim())){
					String sql=qdCompareCond.getSql();
					if(sql!=null && !"".equals(sql.toString().trim())){
						List l = this.jdbcTemplate.queryForList(sql);
						if(l!=null && l.size()>0){
							for(int i=0;i<l.size();i++){
								ListOrderedMap lom = (ListOrderedMap)l.get(i);							
								Map t = new HashMap();
								t.put("code", lom.get(lom.get(0)));
								t.put("name", lom.get(lom.get(1)));
								t.put("pcode",lom.get(lom.get(2)));
								t.put("isprocess","0");				
								if(lom.get(lom.get(2))==null || "".equals(lom.get(lom.get(2)).toString().trim())){									
									retProcessList.add(t);
								}
								retList.add(t);
							}						
						}
					}
				}				
			}
			
			if(retProcessList!=null && retProcessList.size()>0){
				for(int i=0;i<retProcessList.size();i++){
					Map m = (Map)retProcessList.get(i);
					String id = null;
					String text = null;
					if(m.get("code")!=null){
						id = m.get("code").toString();
					}

					if(m.get("name")!=null){
						text = m.get("name").toString();
					}
									
					String childNodeStr = getChildrenNode(id,retList);
					if(childNodeStr!=null && !"".equals(childNodeStr.toString().trim())){
						if(jasonString!=null && !"".equals(jasonString.toString().trim())){
							jasonString = jasonString+",{'text':'"+text+"','id':'"+id+"','leaf':false,'checked':false,'children':"+childNodeStr+"}";
						}else{
							jasonString = "[{'text':'"+text+"','id':'"+id+"','leaf':false,'checked':false,'children':"+childNodeStr+"}";
						}
					}else{
						if(jasonString!=null && !"".equals(jasonString.toString().trim())){
							jasonString = jasonString+",{'text':'"+text+"','id':'"+id+"','leaf':true,'checked':false,'children':[]}";
						}else{
							jasonString = "[{'text':'"+text+"','id':'"+id+"','leaf':true,'checked':false,'children':[]} ";
						}
					}
				}
				if(jasonString!=null && !"".equals(jasonString.toString().trim())){
					jasonString = jasonString+"]";
				}
			}
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		return jasonString;
	}
	
	
	/**
	 * @descript 获取子节点数据
	 * @param pid
	 * @param processList
	 * @return String
	 */
	private String getChildrenNode(String pid,List processList){
		String jasonString = "";
		if(processList!=null && processList.size()>0){
			for(int i=0;i<processList.size();i++){
				Map m = (Map)processList.get(i);
				String id = null;
				String text = null;
				String parent_id = null;
				if(m.get("code")!=null){
					id = m.get("code").toString();
				}

				if(m.get("name")!=null){
					text = m.get("name").toString();
				}
				
				if(m.get("pcode")!=null){
					parent_id = m.get("pcode").toString();
				} 
				
				if(m.get("pcode")!=null && !"".equals(m.get("pcode").toString().trim()) && m.get("isprocess")!=null  && "0".equals(m.get("isprocess").toString().trim()) ){
					if(parent_id!=null && pid.toString().trim().equals(parent_id.toString().trim())){
						m.put("isprocess", "1");
						String childNodeStr = getChildrenNode(id,processList);
						if(childNodeStr!=null && !"".equals(childNodeStr.toString().trim())){
							if(jasonString!=null && !"".equals(jasonString.toString().trim())){
								jasonString = jasonString+",{'text':'"+text+"','id':'"+id+"','leaf':false,'checked':false,'children':"+childNodeStr+"}";
							}else{
								jasonString = "[{'text':'"+text+"','id':'"+id+"','leaf':false,'checked':false,'children':"+childNodeStr+"}";
							}
						}else{
							if(jasonString!=null && !"".equals(jasonString.toString().trim())){
								jasonString = jasonString+",{'text':'"+text+"','id':'"+id+"','leaf':true,'checked':false,'children':[]}";
							}else{
								jasonString = "[{'text':'"+text+"','id':'"+id+"','leaf':true,'checked':false,'children':[]} ";
							}
						}			
					}
				}
			}
			
			if(jasonString!=null && !"".equals(jasonString.toString().trim())){
				jasonString = jasonString+"]";
			}
		}
		return jasonString;
	}
	
	/**
	 * @descripte 获取查询条件下拉列表内容。
	 * @param id 查询条件字段ID号
	 * @return List  0 value 1 text 
	 */
	@SuppressWarnings({ "unchecked", "unchecked" })
	public List getSearchConditionTypeSQLList(String id){
		List retList = null;		
		try{
			if(id!=null && !"".equals(id.toString().trim())){
				QdCompareCond qdCompareCond = (QdCompareCond)this.hibernateTemplate.get(QdCompareCond.class, id.toString().trim());
				if(qdCompareCond!=null && qdCompareCond.getId()!=null && !"".equals(qdCompareCond.getId().toString().trim())){
					String sql = qdCompareCond.getSql();
					if(sql!=null && !"".equals(sql.toString().trim())){
						retList = this.jdbcTemplate.queryForList(sql.toString().trim());
					}
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
			retList = null;
		}
		return retList;
	}
	
	
	/**
	 * @descripte 根据主题获取主题所在位置标题
	 * @param qdDomain 主题
	 * @return String 
	 */
	@SuppressWarnings("unchecked")
	public String getTitle(QdDomain qdDomain){
		String retTitle = null;
		try{
			if(qdDomain!=null && qdDomain.getId()!=null && !"".equals(qdDomain.getId().toString().trim())){
				String functionId = qdDomain.getFunctionId();
				if(functionId!=null && !"".equals(functionId.toString().trim())){
					String sql = " select a.name as name from t_function a CONNECT BY a.id = PRIOR a.parent_id START WITH a.id = '"+functionId+"'";
					List retList = this.jdbcTemplate.queryForList(sql);
					if(retList !=null && retList.size()>0){
						for(int i=0;i<retList.size();i++){
							Map m = (Map)retList.get(i);
							if(m!=null && !m.isEmpty() && m.get("name")!=null && !"".equals(m.get("name").toString().trim())){
								if(retTitle==null){
									retTitle = m.get("name").toString().trim();
								}else{
									retTitle = m.get("name").toString().trim()+"-"+retTitle;
								}
							}
						}
						
					}					
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
			retTitle = null;
		}
		return retTitle;
	}
	
	
	
	/**
	 * @descript 高级查询
	 * @param strDomainId
	 * @param qdSimplemeasuList
	 * @param condstr
	 * @param orderstr
	 * @param orderstrtype
	 * @param pageNo
	 * @param pageSize
	 * @return
	 */
	public Object[] doHightSearch(String strDomainId,List<QdSimplemeasu> qdSimplemeasuList,String condstr, String orderstr,String orderstrtype ,int pageNo, int pageSize){
		Object[] retString = new Object[3];		
		Page page = null;
		String  sql = "";
		int countField = 0;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				//组装查询条件
				String strCond = "";
				if(qdSimplemeasuList!=null && qdSimplemeasuList.size()>0  &&	condstr!=null	&& !"".equals(condstr.toString().trim()) ){
					String[] condstrArr = condstr.split("######");
					if(condstrArr!=null && condstrArr.length>0){
						for(int i=0;i<condstrArr.length;i++){
							if(condstrArr[i]!=null && !"".equals(condstrArr[i].toString().trim()) && !"null".equals(condstrArr[i].toString().trim())){
								strCond = strCond+condstrArr[i].toString().trim()+" ";
							}							
						}
					}			
				}
				//拼接SQL语句
				String[] retSqlString = ConnectCond(strDomainId,qdSimplemeasuList,strCond);
				sql = retSqlString[0].toString();
				countField = Integer.parseInt(retSqlString[1].toString());
				
				//组装排序条件
				String orderStrField = "";
				if(orderstr!=null && !"".equals(orderstr.toString().trim())){
					List<QdSimplemeasu> orderFieldList = getFieldList(strDomainId,orderstr, "2");
					String[] orderstrArr =orderstr.split("######");
					String[] orderstrtypeArr = orderstrtype.split("######");					
					if(orderFieldList!=null && orderFieldList.size()>0){
						for(int i=0;i<orderFieldList.size();i++){
							QdSimplemeasu qdSimplemeasu = orderFieldList.get(i);
							if(qdSimplemeasu!=null && qdSimplemeasu.getId()!=null && !"".equals(qdSimplemeasu.getId().toString().trim())){
								for(int j=i;j<orderstrArr.length;j++){
									if(orderstrArr[j]!=null && !"".equals(orderstrArr[j].toString().trim()) && !"null".equals(orderstrArr[j].toString().trim())											
											&& orderstrtypeArr[j]!=null && !"".equals(orderstrtypeArr[j].toString().trim()) && !"null".equals(orderstrtypeArr[j].toString().trim())
													&& qdSimplemeasu.getId().toString().trim().equals(orderstrArr[j].toString().trim())){
										if(orderStrField!=null && !"".equals(orderStrField.toString().trim())){
											orderStrField = orderStrField+", "+qdSimplemeasu.getCol()+" "+orderstrtypeArr[j].toString().trim();								
										}else{
											orderStrField = " order by "+ qdSimplemeasu.getCol() +" "+orderstrtypeArr[j].toString().trim();
										}
										j=orderstrArr.length;
									}
								}								
							}							
						}
						
					}					
				}
				if(orderStrField!=null && !"".equals(orderStrField.toString().trim())){
					sql+= orderStrField;
				}
				
				//执行查询
				if(sql!=null && !"".equals(sql.toString().trim())){
					if (pageNo <= 0) pageNo = 1;
					StringBuffer sb = new StringBuffer(sql);
					Map params = new HashMap();
					HibernateCallback action = HibernateCallbackUtil.getCallbackWithPage(sb, null,true,null, pageNo, pageSize);					
					page = (Page)hibernateTemplate.execute(action);
				}
				
			}	
		}catch(Exception e){
			e.printStackTrace();
			page = null;
			sql = null;
		}
		retString[0]=page;
		retString[1]=sql;
		retString[2]=countField;
		return retString;
	}
	
	
	
	/**
	 * @descript excel导出查询
	 * @param strDomainId
	 * @param qdSimplemeasuList
	 * @param condstr
	 * @param orderstr
	 * @param orderstrtype
	 * @return
	 */
	public List doExportForExcel(String strDomainId,List<QdSimplemeasu> qdSimplemeasuList,String condstr, String orderstr,String orderstrtype ){		
		List dataList = null;
		String  sql = "";
		int countField = 0;
		try{
			if(strDomainId!=null && !"".equals(strDomainId.toString().trim())){
				//组装查询条件
				String strCond = "";
				if(qdSimplemeasuList!=null && qdSimplemeasuList.size()>0  &&	condstr!=null	&& !"".equals(condstr.toString().trim()) ){
					String[] condstrArr = condstr.split("######");
					if(condstrArr!=null && condstrArr.length>0){
						for(int i=0;i<condstrArr.length;i++){
							if(condstrArr[i]!=null && !"".equals(condstrArr[i].toString().trim()) && !"null".equals(condstrArr[i].toString().trim())){
								strCond = strCond+condstrArr[i].toString().trim()+" ";
							}							
						}
					}			
				}
				//拼接SQL语句
				String[] retSqlString = ConnectCond(strDomainId,qdSimplemeasuList,strCond);
				sql = retSqlString[0].toString();
				countField = Integer.parseInt(retSqlString[1].toString());
				
				//组装排序条件
				String orderStrField = "";
				if(orderstr!=null && !"".equals(orderstr.toString().trim())){
					List<QdSimplemeasu> orderFieldList = getFieldList(strDomainId,orderstr, "2");
					String[] orderstrArr =orderstr.split("######");
					String[] orderstrtypeArr = orderstrtype.split("######");					
					if(orderFieldList!=null && orderFieldList.size()>0){
						for(int i=0;i<orderFieldList.size();i++){
							QdSimplemeasu qdSimplemeasu = orderFieldList.get(i);
							if(qdSimplemeasu!=null && qdSimplemeasu.getId()!=null && !"".equals(qdSimplemeasu.getId().toString().trim())){
								for(int j=i;j<orderstrArr.length;j++){
									if(orderstrArr[j]!=null && !"".equals(orderstrArr[j].toString().trim()) && !"null".equals(orderstrArr[j].toString().trim())											
											&& orderstrtypeArr[j]!=null && !"".equals(orderstrtypeArr[j].toString().trim()) && !"null".equals(orderstrtypeArr[j].toString().trim())
													&& qdSimplemeasu.getId().toString().trim().equals(orderstrArr[j].toString().trim())){
										if(orderStrField!=null && !"".equals(orderStrField.toString().trim())){
											orderStrField = orderStrField+", "+qdSimplemeasu.getCol()+" "+orderstrtypeArr[j].toString().trim();								
										}else{
											orderStrField = " order by "+ qdSimplemeasu.getCol() +" "+orderstrtypeArr[j].toString().trim();
										}
										j=orderstrArr.length;
									}
								}								
							}							
						}
						
					}					
				}
				if(orderStrField!=null && !"".equals(orderStrField.toString().trim())){
					sql+= orderStrField;
				}
				
				//执行查询
				if(sql!=null && !"".equals(sql.toString().trim())){
					dataList = this.jdbcTemplate.queryForList(sql);
				}
				
			}	
		}catch(Exception e){
			e.printStackTrace();
			dataList = null;
		}
		
		return dataList;
	}
	
	
	
	private String replaceSysParam(String con){
		if(con!=null && !"".equals(con.toString().trim())){
			if(con.indexOf(SysArgUtil.SYSPARAM_USERID)!=-1){
				User user = UserUtil.getCurrentUser();
				
				//计算字串数目
				int count=0;
				int ip=0;
				String splitStr = con;				
				while(ip!=-1){
				   ip=splitStr.indexOf(SysArgUtil.SYSPARAM_USERID);				   
				   splitStr=splitStr.substring(ip+SysArgUtil.SYSPARAM_USERID.length());				   
				   if(ip!=-1) count++;
				}	
				
				//替换字串
				for(int i=0;i<count;i++){
					if(user!=null && user.getUsername()!=null){
						con= con.substring(0,con.indexOf(SysArgUtil.SYSPARAM_USERID))+user.getUsername().toString().trim()+con.substring(con.indexOf(SysArgUtil.SYSPARAM_USERID)+SysArgUtil.SYSPARAM_USERID.length());					
					}else{
						con= con.substring(0,con.indexOf(SysArgUtil.SYSPARAM_USERID))+con.substring(con.indexOf(SysArgUtil.SYSPARAM_USERID)+SysArgUtil.SYSPARAM_USERID.length());					
					}				
				}
			}
		}
		return con;		
	}

}
